use sqlx::SqlitePool;

#[derive(Debug, Clone)]
pub struct Config {
    pub database_url: String,
    pub jwt_secret_key: String,
    pub jwt_max_age: i64,
}

impl Config {
    pub fn init() -> Self {
        let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
        let jwt_secret_key = std::env::var("JWT_SECRET_KEY").expect("JWT_SECRET_KEY must be set");
        let jwt_max_age = std::env::var("JWT_MAXAGE").expect("JWT_MAXAGE must be set");

        Self {
            database_url,
            jwt_secret_key,
            jwt_max_age: jwt_max_age.parse::<i64>().unwrap(),
        }
    }
}

#[derive(Debug)]
pub struct DBClient {
    pub pool: SqlitePool,
}

impl DBClient {
    pub async fn init(config: &Config) -> Self {
        let pool = match sqlx::sqlite::SqlitePoolOptions::new()
            .max_connections(2)
            .connect(&config.database_url)
            .await
        {
            Ok(pool) => {
                println!("Connection to the database is successful!");
                pool
            }
            Err(err) => {
                println!("Failed to connect to the database: {:?}", err);
                std::process::exit(1);
            }
        };

        Self { pool }
    }
}
